/**************************************************************************
 * @name: msg_rcv.c
 * @brief: 这是学习消息队列的代码案例
 * @date: 2025/02/11
 * @author: boluzs@163.com
 * @note: None
 * @version: 1.0.0
 * @Copyright (c) 2025 by boluzs@163.com, All Rights Reserved.
 **************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <time.h>
#include <unistd.h>

typedef struct order
{
    char order[16];
    char pay[16];
    char time[32];
} order_t, *order_p;

typedef struct msgbuf
{
    long mtype;
    order_t order_data;
} msg_t, *msg_p;

int queue_id = 0;

/**************************************************************************
 * @name: create_queue
 * @brief: 创建消息队列
 * @note: None
 * @retval: None
 **************************************************************************/
void create_queue(void)
{
    queue_id = msgget(ftok(".", 1), IPC_CREAT | 0666);
    if (queue_id == -1)
    {
        fprintf(stderr, "创建队列失败,error=%d,%s\n", errno, strerror(errno));
    }
    printf("创建的队列ID:%d\n", queue_id);
}

/**************************************************************************
 * @name: get_msg
 * @brief: 获取消息队列中的队列
 * @note: None
 * @retval: None
 **************************************************************************/
void get_msg(void)
{

    while (1)
    {
        msg_p msg_data = (msg_p)calloc(1, sizeof(msg_t));
        char *Date_Str = (char *)calloc(1, 32);
        msgrcv(queue_id, msg_data, sizeof(order_t), 1, IPC_NOWAIT);
        printf("当前订单数据:%s,%s,%s\n", msg_data->order_data.order, msg_data->order_data.pay, msg_data->order_data.time);
        free(msg_data);
        free(Date_Str);
        sleep(5);
    }
}

int main(int argc, char const *argv[])
{
    create_queue();
    get_msg();
    return 0;
}
